<?php

namespace app\api\model;

use app\api\logic\LogicalProcess;
use lunzi\TpSms;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\Model;
use function DI\string;

class Member extends Model
{
    // 设置数据表名称
    protected $name = "member";


    //获取用户信息
    public function userInfo($uid)
    {
        $res['sysUser'] = self::where("status", 1)->field("id,avatar,username,member_level,qq,wechat,nickname,invite_code,mobile,random_uid")->find($uid);
        $res['sysUser']['avatar'] = get_image_url($res['sysUser']['avatar']);
        $res['sysUserWallets'] = Db::name("user_wallet")->where("user_id", $uid)->where('status', 1)->field("user_id,type,amount,freeze,status")->select();
        //查询是否有师徒四人
        $nfc = Db::name("user_get_npc")->where("user_id", $uid)->where("type", 1)->find();
        $res['isHaveNfcToFour'] = !empty($nfc);
        //查询全部金箍棒
        $res['allJGB'] = Db::name("user_jgb")->where("user_id", $uid)->count();
        //查询损坏金箍棒
        $res['badJGB'] = Db::name("user_jgb")->where("user_id", $uid)->where("durability", "<>", 30)->where("is_use", false)->count();
        //是否店长
        $shop = Db::name("shop_manager")->where("status", 1)->where("user_id", $uid)->find();
        $res["isShopManager"] = !empty($shop);
        //查询直推人数
        $res['thrust'] = self::where("pid", $uid)->where("mark", 1)->count();
        //查询直推有效人数
        $res['thrustValid'] = Db::name("member")->alias("m")->join("user_npc n", "n.user_id=m.id")->where("m.pid", $uid)->where("n.npc_id", 1)->count();
        return message("操作成功", true, $res);
    }


    //修改信息
    public function updateUserNickName($params)
    {
        $nickname = getter($params, "nickName");
        $token = Cache::store("redis")->get("baidu_token");
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $nickname
        );
        $data = (new LogicalProcess())->solutionVerify($url, $bodys);
        if ($data['conclusionType'] == 2) {
            return message("昵称不合规", false);
        }

        if ($nickname) {
            Db::name("member")->where('id', $params['user_id'])->update(['nickname' => $nickname]);
        }
        return message("操作成功", true);
    }


    //实名认证
    public function authMember($params)
    {
        $model = Db::name("member")->where("id", $params['user_id']);
        //查询是否已认证
        $info = $model->find();
        if ($info['is_auth'] == 2) return message("已实名认证，无需再次认证", false);
        //TODO 实名认证三要素
        $res = (new LogicalProcess())->authVerify($params['mobile'], $params['realname'], $params['idcardno']);
        if ($res['code'] == 200) {
            if ($res['data']['result'] == "1") {
                return message("不一致", false);
            }
        }

        $data = [
            "is_auth" => 2,
        ];

        $model->save($data);
        return message("操作成功", true);
    }

    //社交信息
    public function socializeInfo($params)
    {
        $model = Db::name("member")->where("id", $params['user_id']);
        $data = [
            "qq" => $params['qq'],
            "wechat" => $params['wechat'],
        ];
        $model->save($data);
        return message("操作成功", true);
    }


    //修改支付密码
    public function updatePwd($params)
    {
        //查询当前用户手机号
        $info = self::where("id", $params['user_id'])->find();
//        $check_code = (new TpSms())
//            ->scene("handlePassword")
//            ->mobile($info['mobile'])
//            ->code($params['code'])
//            ->check();
//        if (!$check_code) {
//            return message("验证码错误", false);
//        }
        //验证密码强度
        if (!checkPass($params['newPassword'])) return message("密码强度太低,应包含字母,数字,并且在6位以上", false);
        if (strlen($params['newPassword']) < 6 || strlen($params['newPassword']) > 20) return message("密码长度应在6~20位", false);
        if (get_password($params['oldPassword']) != $info['handlePassword']) return message("旧密码输入错误", false);
        if ($params['oldPassword'] == $params['newPassword']) return message("新密码与旧密码相同", false);
        self::where("id", $params['user_id'])->update(['handle_pass' => get_password($params['newPassword'])]);
        return message("操作成功", true);
    }


    //忘记密码
    public function forgetPwd($params)
    {
        //查询当前用户手机号
        $info = self::where("id", $params['user_id'])->find();
//        $check_code = (new TpSms())
//            ->scene("handlePassword")
//            ->mobile($info['mobile'])
//            ->code($params['code'])
//            ->check();
//        if (!$check_code) {
//            return message("验证码错误", false);
//        }
        if (!checkPass($params['newPassword'])) return message("密码强度太低,应包含字母,数字,并且在6位以上", false);
        if (strlen($params['newPassword']) < 6 || strlen($params['newPassword']) > 20) return message("密码长度应在6~20位", false);
        if ($params['oldPassword'] != $params['newPassword']) return message("两次密码不一致", false);
        self::where("id", $params['user_id'])->update(['handle_pass' => get_password($params['newPassword'])]);
        return message("操作成功", true);
    }


    //店长拥有的npc
    public function getNpfByShopManager($params)
    {
        //查询店长npc
        $list = Db::name("production_npc")->where("status", 1)->where("shop_manager", $params['user_id'])->withoutField("create_user,create_time,update_user,update_time,mark")->select();
        return message("操作成功", true, $list);
    }

    //店长转增用户npc
    public function giftNfcToUser($params)
    {
        //查询用户信息
        $user = self::where("invite_code", $params['inviteCode'])->where("status", 1)->where("mark", 1)->find();
        if (empty($user)) return message("未查询到用户,请检查用户状态", false);

        //查询店长信息
        $shopManager = Db::name("shop_manager")->where("user_id", $params['user_id'])->where("status", 1)->find();
        if (empty($shopManager)) return message("未查询到店长信息,请检查店长状态", false);
        //查询店长密码
        $password = self::where("id", $params['user_id'])->value("handle_pass");
        //验证密码
//        if (get_password($params['password']) != $password) return message("安全密码错误，不可转增", false);
        //ids 转为数组
        $ids = explode(",", $params['nfcIds']);
        if (empty($ids)) return message("请选择需转增的npc", false);
        $production = Db::name("production_npc")->whereIn("id", $ids)->select()->toArray();
        foreach ($production as $v) {
            Db::name("user_take_nfc")->insert([
                "shop_manager_id" => $params['user_id'],
                "user_id" => $user['id'],
                "production_nfc_id" => $v['id'],
                "is_take" => false,
                "nfc_type" => 1,
                "nfc_name" => $v['name'],
                "create_time" => datetime(time()),
            ]);
            Db::name("production_npc")->where("id", $v['id'])->update(['status' => 2]);
        }
        return message("操作成功", true);
    }

    //获取已转增的npc
    public function getNfcByIsUse($params)
    {

        $list = Db::name("production_npc")->where("shop_manager", $params['user_id'])->where('status', 2)->withoutField("create_user,create_time,update_user,update_time,mark")->select();

        return message("操作成功", true, $list);
    }

    //用户获取取货单
    public function getTakeData($params)
    {
        $list = Db::name("user_take_nfc")->where("user_id", $params['user_id'])->select();
        return message("操作成功", true, $list);
    }

    //店长获取取货单
    public function getTakeDataByShopManager($params)
    {
        $list = Db::name("user_take_nfc")->where("shop_manager_id", $params['user_id'])->select();
        return message("操作成功", true, $list);
    }

    //用户取货
    public function takeNfc($params)
    {
        //查询取货单是否存在
        $takeNpc = Db::name("user_take_nfc")->where("id", $params['id'])->find();
        if (empty($takeNpc)) return message("未查询到取货单，请联系店长", false);
        if ($takeNpc['user_id'] != $params['user_id']) return message("取货人信息不匹配，请联系店长", false);
        if ($takeNpc['is_take'] == true) return message("不可重复领取", false);
        Db::name("user_take_nfc")->where("id", $params['id'])->update([
            "is_take" => true,
            "address" => $params['address'],
            "take_time" => datetime(time()),
            "remake" => $params['remake'],
        ]);
        //查询生产情况
        $npc = Db::name("production_npc")->where("id", $takeNpc['production_nfc_id'])->where("type", 1)->find();
        if (empty($npc)) return message("npc异常，请联系店长", false);
        //查询玩家npc记录
        $userNpc = Db::name("user_npc")->where("user_id", $params['user_id'])->where("npc_id", 1)->find();
        $npcDataArray = [];
        if (empty($userNpc)) {
            $npcConfig = Db::name("npc")->select()->toArray();
            $data = [
                "user_id" => $params['user_id'],
                "shop_manager_id" => $npc['shop_manager'],
                "lv" => 1,
                "create_time" => datetime(time()),
                "exp" => 0,
                "stamina" => 100,
            ];
            foreach ($npcConfig as $v) {
                $data['npc_id'] = $v['id'];
                $npcDataArray[] = $data;
            }
            Db::name("user_npc")->insertAll($npcDataArray);
        } else {
            //查询挖矿配置
            $miningConfig = Db::name("mining_config")->select()->toArray();
            //查询收益
            $queryEarnings = (new LogicalProcess())->queryEarnings($params['user_id']);
            if ($queryEarnings['code'] == -1) return message($queryEarnings['msg'], false);
            switch ($userNpc['lv']) {
                case 1:
                    if ($userNpc['activate_time'] != null) {
                        //生成领取记录
                        Db::name("user_get_record")->insert([
                            "user_id" => $params['user_id'],
                            "create_time" => time(),
                            "amount" => $queryEarnings['data']['amountTotal'],
                        ]);
                        //钱包操作
//                        (new LogicalProcess())->wallletChange($params['user_id'], $queryEarnings['data']['amountTotal'], 3, 1, 1, "联盟打怪，领取经书");
                    }
                    $exp = 0;
                    $lvUp = 2;
                    break;
                case 2:
                    $exp = $userNpc['exp'] + 1;
                    if ($exp >= $miningConfig['lv_two_exp']) {
                        if ($userNpc['activate_time'] != null) {
                            //生成领取记录
                            Db::name("user_get_record")->insert([
                                "user_id" => $params['user_id'],
                                "create_time" => time(),
                                "amount" => $queryEarnings['data']['amount'],
                            ]);
                            //钱包操作
//                            (new LogicalProcess())->wallletChange($params['user_id'], $queryEarnings['data']['amountTotal'], 3, 1, 1, "联盟打怪，领取经书");
                        }
                        $exp = 0;
                        $lvUp = 2;
                    }
                    break;
                case 3:
                    $exp = $userNpc['exp'] + 1;
                    if ($exp >= $miningConfig['lv_two_exp']) {
                        if ($userNpc['activate_time'] != null) {
                            //生成领取记录
                            Db::name("user_get_record")->insert([
                                "user_id" => $params['user_id'],
                                "create_time" => time(),
                                "amount" => $queryEarnings['data']['amount'],
                            ]);
                            //钱包操作
//                            (new LogicalProcess())->wallletChange($params['user_id'], $queryEarnings['data']['amountTotal'], 3, 1, 1, "联盟打怪，领取经书");
                        }
                        $exp = 0;
                        $lvUp = 4;
                    }
                    break;
                case 4:
                    $exp = $userNpc['exp'] + 1;
                    if ($exp >= $miningConfig['lv_two_exp']) {
                        if ($userNpc['activate_time'] != null) {
                            //生成领取记录
                            Db::name("user_get_record")->insert([
                                "user_id" => $params['user_id'],
                                "create_time" => time(),
                                "amount" => $queryEarnings['data']['amount'],
                            ]);
                            //钱包操作
//                            (new LogicalProcess())->wallletChange($params['user_id'], $queryEarnings['data']['amountTotal'], 3, 1, 1, "联盟打怪，领取经书");
                        }
                        $exp = 0;
                        $lvUp = 5;
                    }
                    break;
                case 5:
                    $exp = 0;
                    $lvUp = 5;
                    break;
            }
            Db::name("user_npc")->where("user_id", $params['user_id'])->where("npc_id", 1)->update([
                "exp" => $exp,
                "lv" => $lvUp,
            ]);

        }
        //添加兑换记录
        Db::name("user_get_npc")->insert(
            [
                "user_id" => $params['user_id'],
                "shop_manager_id" => $npc['shop_manager'],
                "production_id" => $takeNpc['production_nfc_id'],
                "check_code" => $npc['check_code'],
                "production_batch" => $npc['production_batch'],
                "create_time" => time(),
            ]
        );
        return message("操作成功", true);
    }

    //用户激活悟空挖矿
    public function activateWuKong($params)
    {
        //查询npc兑换记录
        $userGetNpc = Db::name("user_get_npc")->where("check_code", $params['checkCode'])->where("user_id", $params['user_id'])->find();
        if (empty($userGetNpc)) return message("npc校验异常,请联系管理员", false);
        //校验生产记录
        $product = Db::name("production_npc")->where("check_code", $params['checkCode'])->where("status", 2)->where("type", 1)->find();
        if (empty($product)) return message("nfc校验异常,请联系管理员", false);
        //取货单校验
        $takeNpc = Db::name("user_take_nfc")->where("production_nfc_id", $product['id'])->where("is_take", 1)->find();
        if (empty($takeNpc)) return message("取货单异常,请联系管理员", false);
        //改变悟空状态
        $userNpc = Db::name("user_npc")->where("user_id", $params['user_id'])->where("npc_id", 1)->update(['activate_time' => datetime(time())]);
        if (!$userNpc) return message("激活失败请重试", false);
        //升级上级用户
        $group = self::where("status", 1)->where("mark", 1)->where("id", $params['user_id'])->value("group");
        if (!$group) return message("激活成功", true);
        //查询联盟等级
        $level = Db::name("league_config")->where("mark", 1)->order("league_lv asc")->select()->toArray();
        $parentArray = explode(",", $group);
        //查询直推
        foreach ($parentArray as $pid) {
            //根据上级id 查询直推人数
            $teamCount = self::where("pid", $pid)->where("status", 1)->where("mark", 1)->count();
            //根据上级id 查询团队人数
            $groupCount = self::whereFindInSet("group", $pid)->where("status", 1)->where("mark", 1)->count();
            foreach ($level as $item) {
                if ($teamCount < $item['team_member'] || $groupCount < $item['league_team_member']) break;
                self::where("id", $pid)->update(['lv' => $item['league_lv']]);
            }
        }
        return message("操作成功", true);
    }


    //转增经书
    public function giftBookSToUser($params)
    {
        //获取被转增人信息
        $beInfo = self::where("invite_code", $params['uid'])->where("status", 1)->where("mark", 1)->find();
        if (empty($beInfo)) return message("受赠用户身份校验未通过", false);
        //转增人信息
        $transInfo = self::where("id", $params['user_id'])->where("status", 1)->where("mark", 1)->find();
        if (empty($transInfo)) return message("转赠用户身份校验未通过", false);
//        if (get_password($params['payPwd']) != $transInfo['handle_pass']) return message("安全密码错误，请重试", false);
        if ($params['total'] <= 0) return message("转增金额异常", false);
        //查询是否是店长
        $shop = Db::name("shop_manager")->where("status", 1)->where("user_id", $params['user_id'])->find();
        //获取手续费
        $game = Db::name("game_config")->where("id", 1)->field("shop_gift_fee,user_gift_fee")->find();
        $fee = $game['user_gift_fee'] / 100;
        if ($shop) {
            $fee = $game['shop_gift_fee'] / 100;
        }
        $feeTotal = bcmul((string)$params['total'], $fee, 6);
//        if ($feeTotal != $params['feeTotal']) return message("手续费异常", false);
        (new LogicalProcess())->wallletChange($beInfo['id'], $params['total'], 8, 1, 1, "获取转增经书");
        (new LogicalProcess())->wallletChange($params['user_id'], bcadd((string)$params['total'], $feeTotal, 6), 8, 2, 1, "转增经书");
        //增加转增记录
        $giftRecord = Db::name("gift_record")->insert([
            "gift_user_id" => $params['user_id'],
            "be_gift_user_id" => $beInfo['uid'],
            "total" => $params['total'],
            "fee_total" => $params['feeTotal'],
            "create_time" => time(),
        ]);
        return message("操作成功", true);
    }

    //转增记录  受赠记录
    public function getGiftRecord($params)
    {
        $str = "g.gift_user_id";
        $string = "gift_user_id";
        if ($params['type'] == 1) {
            $str = "g.be_gift_user_id";
            $string = "be_gift_user_id";
        }
        $page = $params['pageNum'] ? $params['pageNum'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        $count = Db::name("gift_record")->where($string, $params['user_id'])->count();
        $list = Db::name("gift_record")
            ->alias("g")
            ->where($str, $params['user_id'])
            ->leftjoin("evt_member m1", "m1.id=g.gift_user_id")
            ->leftJoin("evt_member m2", "m2.id=g.be_gift_user_id")
            ->field("g.*,m1.nickname as giftName,m2.nickname as beGiftName")
            ->page($page, $pageSize)->select()->toArray();
        $res = [
            "count" => $count,
            'list' => $list,
        ];
        return message("操作成功", true, $res);

    }

    //邀请统计
    public function getInviteStat($userId): array
    {
        //查询我的直推有效，直推无效
        $thrust = Db::name("member")->where("pid", $userId)->where("mark", 1)->count();
        $eliteTeammateNum = Db::name("member")->alias("m")->join("user_npc n", "n.user_id=m.id")->where("m.pid", $userId)->where("n.npc_id", 1)->count();
        $teammateNum = $thrust - $eliteTeammateNum;

        //查询我的团队有效，团队无效
        $team = Db::name("member")->whereFindInSet("group", $userId)->where("mark", 1)->count();
        $eliteLeagueNum = Db::name("member")->alias("m")->join("user_npc n", "n.user_id=m.id")->whereFindInSet("m.group", $userId)->where("n.npc_id", 1)->count();
        $leagueNum = $team - $eliteLeagueNum;
        $totalDistribution = Db::name("distribution")->where("uid", $userId)->sum("amount");
        $res = [
            "eliteTeammateNum" => $eliteTeammateNum,
            "teammateNum" => $teammateNum,
            "leagueNum " => $leagueNum,
            "eliteLeagueNum " => $eliteLeagueNum,
            "totalDistribution " => $totalDistribution,
        ];
        return message("操作成功", true, $res);
    }

    //获取经书变动记录 排除转增
    public function getBooksChangeRecord($params)
    {
        $page = $params['pageNum'] ? $params['pageNum'] : 1;
        $pageSize = $params['pageSize'] ? $params['pageSize'] : 10;
        $count = Db::name("member_wallet_log")->where("uid", $params['user_id'])->where("category", $params['walletType'])->where('type', $params['changeType'])->whereNotIn("type", [11, 12])->count();
        $wallet = Db::name("member_wallet_log")->where("uid", $params['user_id'])->where("category", $params['walletType'])->where('type', $params['changeType'])->whereNotIn("type", [11, 12])->withoutField("create_user,update_user,update_time,mark")->page($page, $pageSize)->select()->toArray();
        if (empty($wallet)) return message("操作成功", true);
        foreach ($wallet as &$v) {
            $v['create_time'] = datetime($v['create_time']);
        }
        $res = [
            "count" => $count,
            'list' => $wallet,
        ];
        return message("操作成功", true, $res);
    }

}